<?php
/**
 * 移动端客源控制器
 * User: Wu Ning
 * Date: 2018-08-21
 * Time: 18:05
 */
namespace App\Http\Controllers\Mobile\Customer;
use App\Http\Controllers\Backstage\AreaController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\CustomersVail;
use App\Model\Account\SystemType;
use App\Model\Backstage\CustomersFollow;
use App\Model\Mobile\MobilePlan;
use App\Tool\Error;
use Illuminate\Http\Request;
use App\Model\Backstage\Customers;
use Illuminate\Support\Facades\DB;
use Validator;
use Illuminate\Support\Facades\Redis;
class CustomersController extends Controller
{
    /**APP端  客源列表
     * @param Request $request
     * @param Customers $customers
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function appListCustomers(Request $request,Customers $customers)
    {
        $parameter = $request->except('apptoken');
        $validator = CustomersVail::condition($parameter);
        if (!$validator){
            return $this->error(Error::PARAM_MISSING);
        }
        $where = [];
        $where[] = ['c_status', '=', 1];//过滤非回收站房源
        $authories = explode(',', $request->input('authories'));//该员工拥有的所有权限
        //客源查看权限   全部 108  跨部 109   本部 110 本人 111
        //按照该员工查看客源列表的权限
        if (in_array(109, $authories)){ //跨部
            $where[] = ['c_store_id', '<>', $parameter['system_id']];
        } elseif (in_array(110, $authories)){//本部
            $where[] = ['c_store_id', '=', $parameter['did']];
        } elseif (in_array(111, $authories)){//本人
            $where[] = ['c_employees_id', '=', $parameter['uid']];
        }
        //日期 根据委托时间查询
        //委托时间 开始时间
        if ($request->input('start_time')) {
            $where[] = ['c_entrust_time', '>=', strtotime($parameter['start_time'].' 00:00:00')];
        } else {
            $where[] = ['c_entrust_time', '>=', strtotime(date('Y-m-d',strtotime('-12 month')).' 00:00:00')];
        }
        //交易类型 1求购 2求租  451求购 452求租 453租购
        if($request->input('c_trading_type') == 1){
            $where[] = ['c_trading_type','<>',452];
            //购房屋价格 最小值
            if ($request->input('c_price_min')){
                $where[] = ['c_price_min', '>=', $parameter['c_price_min']];
            }
            //购房屋价格 最大值
            if ($request->input('c_price_max')){
                $where[] = ['c_price_max', '<=', $parameter['c_price_max']];
            }
        }elseif ($request->input('c_trading_type') == 2) {
            $where[] = ['c_trading_type','<>',451];
            //租房价格最小值
            if($request->input('c_rent_price_min')){
                $where[] = ['c_rent_price_min','>=',$parameter['c_price_min']];
            }
            //租房价格最大值
            if($request->input('c_rent_price_max')){
                $where[] = ['c_rent_price_max','<=',$parameter['c_price_max']];
            }
        }
        //用途 1 住宅、商住   2 写字楼

        if ($request->input('c_use_type') == 1){
            $where[] = ['c_use_type', '<=', 4];
        } elseif ($request->input('c_use_type') == 2) {
            $where[] = ['c_use_type',  7];
        }

        //房型
        if ($request->input('c_room')){
            $where[] = ['c_room',  $parameter['c_room']];
        }
        //智能查询(keywords)
        $keywords = '';
        if ($request->input('keywords')){
            $keywords = trim($request->input('keywords'));
        }
        $list = $customers->listCustomers(env('PAGE_LIMIT_INDEX'), $where, $keywords, 1);//传1  是APP 端的;
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        $mobilePlan = new MobilePlan();
        $follow = new CustomersFollow();
        foreach ($list as $key=>$val) {
            $val->lookStatus = 1;
            //如果是公客   先根据是不是自己的客源做判断 在根据权限做判断 在根据当天有没有写过跟进做判断
            //看客户不必写跟进 163
            if ($val->c_private_guest == 2 &&  $val->c_employees_id != $parameter['uid'] && !in_array(163, $authories)) {
                //根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
                $res  = $follow->getFollowDay($val->c_id, $parameter['uid']);
//                //最后跟进的天  不是今天的话
                if ($res === 2) {
                    $val->lookStatus = $res;
                    $val->c_user_name = '***';
                    $val->c_user_phone = '***********';
                    $val->c_contact = '***';
                    $val->c_contact_type = '***********';
                    $val->c_address = '**************';
                }
            }
            $val->c_entrust_time = $val->c_entrust_time != null ? date('Y-m-d',$val->c_entrust_time) : '';//委托时间
            $val->c_area_address = $val->c_area_address != null ? $val->c_area_address  : '';//地址
            $val->c_floor = $val->c_floor != null ? $val->c_floor  : '';//楼层
            //客源类型是私客 &&没有查看私客的权限 &&录入人不是登录人
            if ($val->c_private_guest == 1 && !in_array(107, $authories) && $val->c_employees_id != $parameter['uid']) {
                $val->c_user_name = '***';
                $val->c_user_phone = '***********';
                $val->c_contact = '***';
                $val->c_contact_type = '***********';
                $val->c_address = '**************';
            }
            $val->c_secondary_area_name    = AreaController::getAreaName($val->c_secondary_area);//区县
            $val->c_trading_type_name      = SystemType::getTypeDetail($val->c_trading_type);//交易类型
            $val->c_buy_status_name        = SystemType::getTypeDetail($val->c_buy_status);//购买状态
            $val->c_source_type_name       = SystemType::getTypeDetail($val->c_source_type);//来源
            $val->c_entrust_type_name      = SystemType::getTypeDetail($val->c_entrust_type);//委托方式
            $val->c_user_level_name        = SystemType::getTypeDetail($val->c_user_level);//等级
            $val->c_live_type_name         = SystemType::getTypeDetail($val->c_live_type);//现住
            $val->c_professional_type_name = SystemType::getTypeDetail($val->c_professional_type);//类别
            $val->c_user_intention_name    = SystemType::getTypeDetail($val->c_user_intention);//意向
            $val->c_time_limit_name        = SystemType::getTypeDetail($val->c_time_limit);//期限
            $val->c_use_type_name          = SystemType::getTypeDetail($val->c_use_type);//用途
            $val->c_room_type_name         = SystemType::getTypeDetail($val->c_room_type);//房屋类型
            $val->c_toward_name            = SystemType::getTypeDetail($val->c_toward);//朝向
            $val->c_decorate_type_name     = SystemType::getTypeDetail($val->c_decorate_type);//装修
            $val->c_payment_type_name      = SystemType::getTypeDetail($val->c_payment_type);//付款
            //配套名字 c_complete
            $c_complete_name = array();//配套名字
            $completeArr = explode(',', $val->c_complete);
            foreach ($completeArr as $ke=>$va) {
                array_push($c_complete_name, SystemType::getTypeDetail($va));
            }
            $val->c_complete_name = implode(',', $c_complete_name);//配套的名字
            $val->c_pay_type_name      = SystemType::getTypeDetail($val->c_pay_type);//付佣
            //查标记
            $hmp_sign_type = $mobilePlan->getSignType(1, $val->c_id, $parameter['uid']);
            $val->hmp_sign_type = $hmp_sign_type?$hmp_sign_type:0;
        }

        $start_time = null;
        $end_time = strtotime(date('Y-m-d', time()).' 23:59:59');
        return $this->success('ok', $list, $start_time, $end_time);
    }





    /**添加客源信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCustomers(Request $request)
    {
        $params = $request->except('apptoken', 'c_completes', 'c_lots');
        $validator = CustomersVail::add($params);
        if (!$validator) {
            return $this->error(Error::PARAM_MISSING);
        }
        $customers = new Customers();
        $json_info = $request->input('c_room_json','{}');
//        $params['c_room_json'] = json_encode($json_info);
        $params['c_room_json'] = $json_info;
        $params['c_entrust_time'] = strtotime($request->input('c_entrust_time'));

        if ($request->input('c_private_guest')) {//是否是私客
            $params['c_private_guest'] = 1;
        } else {
            $params['c_private_guest'] = 2;
        }
        if ($request->input('c_quality')) {//是否是优质客
            $params['c_quality'] = 1;
        } else {
            $params['c_quality'] = 2;
        }
        $cId = $customers->addCustomers($params);
        if($cId == -1){
            return $this->error(Error::REPEAT_PHONE);
        }
        if (!$cId) {
            return $this->error(Error::ADD_ERROR);
        }
        return $this->success('ok', $cId);

    }

    /**
     * 添加客源跟进
     */
    public function addCustomerFollow(Request $request)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'cf_department_id' => 'required',//部门ID
            'cf_user_id'       => 'required',//员工ID
            'cf_c_id'          => 'required',//客源ID
            'cf_fllow_type'    => 'required',//跟进方式
            'cf_content'       => 'required',//跟进内容
        ]);
        if ($validator->fails()) {
            return $this->error(Error::PARAM_MISSING);
        }
        $params['cf_room_id'] = 0;
        $params['cfs_user_id'] = '';
        $params['cfs_remind_time'] = '';
        $params['cfs_content'] = '';
        $follow = new CustomersFollow();
        $res = $follow->addCustomersFollow($params);
        if (!$res) {
            return   $this->error(Error::ADD_ERROR);
        }
        return $this->success('ok', '添加成功！');
    }


    /**
     * 根据客源id获取客源跟进
     */
    public function customerFollow(Request $request,Customers $customers)
    {
        $customersId = $request->input('cf_c_id');
        $list = $customers->customersFollow($customersId, 3, 1);//APP 传1
        return $this->success('ok', $list);
    }


    //添加、修改客源信息之前  查看该手机号的客源信息是否已经存在
    public function repeatAddition(Request $request,Customers $customers)
    {
        $params = $request->except('apptoken');
        $validator = Validator::make($params, [
            'c_user_phone'   => 'required',
            'authories'      => 'required',
            'uid'            => 'required',
        ]);
        if ($validator->fails()) {
            return $this->error(Error::PARAM_MISSING);
        }
        $c_user_phone = $request->input('c_user_phone');
        $c_id = 0;
        if ($request->input('c_id')) {
            $c_id = $request->input('c_id');//修改有客源ID    添加没有客源ID
        }
        $cid = $customers->whether($c_user_phone, $c_id);
        if ($cid){
            $info = $this->getCustomersInfo($cid);
            if ($info->c_entrust_time) {
                $info->c_entrust_time = substr($info->c_entrust_time,0,10);
            }
            $authories = explode(',', $request->input('authories'));//该员工拥有的所有权限
            //客源类型是私客 &&没有查看私客的权限 &&录入人不是登录人
            if (!in_array(107, $authories) && $info->c_private_guest == 1 && $info->c_employees_id != $params['uid']) {
                $info->c_user_name = '***';
                $info->c_user_phone = '***********';
                $info->c_contact = '***';
                $info->c_contact_type = '***********';
                $info->c_address = '**************';
            }
            //如果是公客   先根据是不是自己的客源做判断 在根据权限做判断 在根据当天有没有写过跟进做判断
            //看客户不必写跟进 163
            if ($info->c_private_guest == 2 &&  $info->c_employees_id != $params['uid'] && !in_array(163, $authories)) {
                //根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
                $follow = new CustomersFollow();
                $res  = $follow->getFollowDay($info->c_id, $params['uid']);
//                //最后跟进的天  不是今天的话
                if ($res === 2) {
                    $info->c_user_name = '***';
                    $info->c_user_phone = '***********';
                    $info->c_contact = '***';
                    $info->c_contact_type = '***********';
                    $info->c_address = '**************';
                }
            }

            return $this->error('error', $info);
        }
        return $this->success('ok', '可以添加');
    }

    //查看录入 修改  有相同手机号客源的信息
    public function getCustomersInfo($cid)
    {
        $customers = new Customers();
        $list = $customers->customersSameList($cid);
        return $list;
    }

    /**
     * APP 写完公客的跟进 根据客源的ID  查询该客源的信息
     */
    public function getCustomersData(Request $request,Customers $customers)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'cf_c_id'          => 'required',//客源ID
        ]);
        if ($validator->fails()) {
            return $this->error(Error::PARAM_MISSING);
        }

        return $this->success('ok', $customers->getImportantInfo($request->input('cf_c_id')));
    }
}
